/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package CA;

import Utility.Certificato;
import Utility.GestioneSQLite;
import Utility.Profilo;
import Utility.Richiesta;
import java.io.IOException;
import java.security.KeyStoreException;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 *
 * @author diego
 */
public class CaGui extends javax.swing.JFrame {

    Ca ca;
    
    public int status_chiamate = -1;
    
    public  static int CERTIFICATI_TUTTI = 0;
    public  static int CERTIFICATI_REVOCATI = 1;
    public  static int CERTIFICATI_VALIDI = 2;
    public  static int CERTIFICATI_RINNOVATI = 3;
    public  static int CERTIFICATI_SCADUTI = 4;
    
    public int visualizzazione_certificati = 0;
    
    /**
     * Creates new form CaGuiNew
     */
    public CaGui() {
        Security.addProvider(new BouncyCastleProvider());  
        
        try {
            ca = new Ca(8080);

        } catch (IOException ex) {
            Logger.getLogger(CaGui.class.getName()).log(Level.SEVERE, null, ex);
            this.status.setText("IOException");
        } catch (KeyStoreException ex) {
            Logger.getLogger(CaGui.class.getName()).log(Level.SEVERE, null, ex);
            this.status.setText("KeyStoreException");
        } catch (CertificateException ex) {
            Logger.getLogger(CaGui.class.getName()).log(Level.SEVERE, null, ex); 
            this.status.setText("CertificateException");
        } catch (Exception ex) {
            Logger.getLogger(CaGui.class.getName()).log(Level.SEVERE, null, ex);
            this.status.setText("Exception");
        }
        
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtable_certificati = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtable_richieste = new javax.swing.JTable();
        jbutton_aggiorna = new javax.swing.JButton();
        jbutton_approva_certificato = new javax.swing.JButton();
        status = new javax.swing.JLabel();
        titolo = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        tutti_certificati = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtable_profili = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        eliminaRichiestaButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jtable_certificati.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jtable_certificati);

        jtable_richieste.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jtable_richieste);

        jbutton_aggiorna.setText("Aggiorna");
        jbutton_aggiorna.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbutton_aggiornaActionPerformed(evt);
            }
        });

        jbutton_approva_certificato.setText("Approva certificato");
        jbutton_approva_certificato.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbutton_approva_certificatoActionPerformed(evt);
            }
        });

        titolo.setFont(new java.awt.Font("Ubuntu", 1, 24)); // NOI18N
        titolo.setText("Pannello di controllo della Certification Autority");

        jButton1.setText("Revoca certificato");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        tutti_certificati.setText("Tutti i certificati");
        tutti_certificati.setActionCommand("tutti_certificati");
        tutti_certificati.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tutti_certificatiActionPerformed(evt);
            }
        });

        jButton2.setText("Certificati revocati");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Certificati validi");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Certificati rinnovati");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Certificati scaduti");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jtable_profili.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane3.setViewportView(jtable_profili);

        jLabel2.setText("Richieste di certificato");

        jLabel3.setText("Utenti registrati");

        jLabel4.setText("Gestione certificati");

        eliminaRichiestaButton.setText("Elimina richiesta");
        eliminaRichiestaButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eliminaRichiestaButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(titolo, javax.swing.GroupLayout.PREFERRED_SIZE, 599, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel1)
                                .addGap(9, 9, 9))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jbutton_aggiorna)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(status, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(0, 0, Short.MAX_VALUE)
                                        .addComponent(eliminaRichiestaButton)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jbutton_approva_certificato))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(tutti_certificati, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(0, 0, Short.MAX_VALUE)))))
                        .addContainerGap())))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(titolo, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbutton_approva_certificato)
                    .addComponent(eliminaRichiestaButton))
                .addGap(3, 3, 3)
                .addComponent(jLabel4)
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton5)
                    .addComponent(jButton4)
                    .addComponent(jButton2)
                    .addComponent(tutti_certificati, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(status, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbutton_aggiorna))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbutton_aggiornaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbutton_aggiornaActionPerformed
    
        this.aggiorna();             
    }//GEN-LAST:event_jbutton_aggiornaActionPerformed

    
    public void aggiorna(){
                    
                Vector <Richiesta> r = GestioneSQLite.retriveRichieste("0");  
                this.popolaTabellaRichieste(r);
                
                Vector <Profilo> profili = GestioneSQLite.retriveProfili();  
                this.popolaTabellaProfili(profili);                

                Vector <Certificato> c = GestioneSQLite.retriveCertificati("0", this.visualizzazione_certificati);                
                this.popolaTabellaCertificati(c,this.visualizzazione_certificati);
                
                this.status.setText(ca.message_gui);
    }
    
    private void popolaTabellaProfili(Vector <Profilo> r){
                    jtable_profili.setModel(new javax.swing.table.DefaultTableModel(
                    //this.data,this.header
                    new Object [][] {
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null},                        
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null},            
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null},                        
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null},
                        {null, null, null, null,null, null}                                    
                    },
                    new String [] {
                        "Nome", "Cognome", "Organizzazione","Unità","Paese","E-mail"
                    }                    
                ));                                              

                for (int i=0; i < r.size(); i++){
                    jtable_profili.getModel().setValueAt(r.get(i).getNome(), i, 0);
                    jtable_profili.getModel().setValueAt(r.get(i).getCognome(), i, 1);
                    jtable_profili.getModel().setValueAt(r.get(i).getOrganizzazione(), i, 2);
                    jtable_profili.getModel().setValueAt(r.get(i).getUnita(), i, 3);   
                    jtable_profili.getModel().setValueAt(r.get(i).getPaese(), i, 4);
                    jtable_profili.getModel().setValueAt(r.get(i).getEmail(), i, 5);                       
                }        
    }
    
    private void popolaTabellaRichieste(Vector <Richiesta> r){
                    jtable_richieste.setModel(new javax.swing.table.DefaultTableModel(
                    //this.data,this.header
                    new Object [][] {
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},                        
                        {null, null, null, null}
                    },
                    new String [] {
                        "Username", "Tipo", "Richiesta","Richiesta rinnovo"
                    }                    
                ));                                              
                
                String tipo;
                for (int i=0; i < r.size(); i++){
                    jtable_richieste.getModel().setValueAt(r.get(i).getUsername(), i, 0);
                    if("1".equals(r.get(i).getTipo())) {
                        tipo="Firma";
                    } else {
                        tipo="Crittografia";
                    }
                    jtable_richieste.getModel().setValueAt(r.get(i).getTipo(), i, 1);
                    jtable_richieste.getModel().setValueAt(r.get(i).getPKCS(), i, 2);
                    jtable_richieste.getModel().setValueAt(r.get(i).getRichiesta_rinnovo(), i, 3);                    
                }        
    }    
    
    private void popolaTabellaCertificati(Vector <Certificato> c, int richiesta_visualizzazione){
                
        jtable_certificati.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},                
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "Username", "Tipo", "Certificato", "Revocato","Rinnovato", "Scadenza", ""
            }
        ));
        
        jtable_certificati.getColumnModel().getColumn(0).setPreferredWidth(150);
        jtable_certificati.getColumnModel().getColumn(1).setPreferredWidth(100);           
        jtable_certificati.getColumnModel().getColumn(2).setPreferredWidth(100);
        jtable_certificati.getColumnModel().getColumn(3).setPreferredWidth(45);
        jtable_certificati.getColumnModel().getColumn(4).setPreferredWidth(45);
        jtable_certificati.getColumnModel().getColumn(5).setPreferredWidth(150);
        jtable_certificati.getColumnModel().getColumn(6).setWidth(0);
        jtable_certificati.getColumnModel().getColumn(6).setMinWidth(0);
        jtable_certificati.getColumnModel().getColumn(6).setMaxWidth(0);
                
        String tipo = null;
        int index_riga_validi = 0;
        int index_riga_scaduti = 0;
        for (int i=0; i < c.size(); i++){
            
            if(richiesta_visualizzazione==CaGui.CERTIFICATI_VALIDI || richiesta_visualizzazione==CaGui.CERTIFICATI_SCADUTI){
                
                String certificato=c.get(i).getCertificato();
                try {
                    if(CaGui.CERTIFICATI_VALIDI==richiesta_visualizzazione){
                        X509Certificate cert = Utility.Utility.creaCertificatoDaStringa(certificato);
                        cert.checkValidity();                    
                        inserisciCertificatoNellaTabella(c.get(i), index_riga_validi);
                        index_riga_validi++;
                    }
                } catch (Exception ex) {
                    if(CaGui.CERTIFICATI_SCADUTI==richiesta_visualizzazione){
                        inserisciCertificatoNellaTabella(c.get(i), index_riga_scaduti);
                        index_riga_scaduti++;
                    }
                }
            }else{
                inserisciCertificatoNellaTabella(c.get(i), i);                
            }           
        }
    }
    
    private void inserisciCertificatoNellaTabella(Certificato c, int i){
        String tipo;
        jtable_certificati.getModel().setValueAt(c.getUsername(), i, 0);
        if("1".equals(c.getTipo())) {
            tipo="Firma";
        } else {
            tipo="Crittografia";
        }                          
        jtable_certificati.getModel().setValueAt(tipo, i, 1);            
        jtable_certificati.getModel().setValueAt(c.getCertificato(), i, 2);            
        jtable_certificati.getModel().setValueAt(c.getRevocato(), i, 3);                                
        jtable_certificati.getModel().setValueAt(c.getRinnovato(), i, 4);            
        jtable_certificati.getModel().setValueAt(c.getData(), i, 5);            
        jtable_certificati.getModel().setValueAt(c.getTipo(), i, 6);           
    }
    
    private void jbutton_approva_certificatoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbutton_approva_certificatoActionPerformed
           // TODO add your handling code here:
            // recupera la richiesta selezionata dal db
            int rigaSelezionata = jtable_richieste.getSelectedRow();
            if(rigaSelezionata > -1){
                String utente = (String) jtable_richieste.getValueAt(rigaSelezionata, 0); 
                String tipo =(String) jtable_richieste.getValueAt(rigaSelezionata, 1);
                String PKCS10 = GestioneSQLite.getRichiestaDiCertificato(utente, tipo);
                String rinnovo =(String) jtable_richieste.getValueAt(rigaSelezionata, 3);
               
                if(ca.creaX509FromPKCS10(PKCS10, utente, tipo, rinnovo)) {
                    this.status.setText("Richiesta del certificato approvata");
                }
                else {
                    this.status.setText("Richiesta del certificato rifiutata");
                }

               
            }else{
                System.err.println("Nessuna richiesta selezionata");
                this.status.setText("Nessuna richiesta selezionata");
            }
            
            this.aggiorna();             
    }//GEN-LAST:event_jbutton_approva_certificatoActionPerformed

    /**
     * Revoca il certificato, inserendolo nella CRL
     * @param evt 
     */
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
         int rigaSelezionata = jtable_certificati.getSelectedRow();
            if(rigaSelezionata > -1){
                String utente = (String) jtable_certificati.getValueAt(rigaSelezionata, 0); 
                String tipo =(String) jtable_certificati.getValueAt(rigaSelezionata, 6);
               
                if(ca.revocaCertificato(utente, tipo)) {
                    this.status.setText("Certificato revocato");
                }
                else {
                    this.status.setText("Certificato non revocato");
                }

               
            }else{
                System.err.println("Nessun certificato selezionato");
                this.status.setText("Nessun certificato selezionato");
            }
            
            this.aggiorna(); 
    }//GEN-LAST:event_jButton1ActionPerformed

    private void tutti_certificatiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tutti_certificatiActionPerformed
        Vector <Certificato> c = GestioneSQLite.retriveCertificati("0", CaGui.CERTIFICATI_TUTTI);                       
        visualizzazione_certificati = CaGui.CERTIFICATI_TUTTI;
        this.popolaTabellaCertificati(c,visualizzazione_certificati);         
    }//GEN-LAST:event_tutti_certificatiActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        Vector <Certificato> c = GestioneSQLite.retriveCertificati("0", CaGui.CERTIFICATI_REVOCATI);                
        visualizzazione_certificati = CaGui.CERTIFICATI_REVOCATI;        
        this.popolaTabellaCertificati(c,visualizzazione_certificati);  
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        Vector <Certificato> c = GestioneSQLite.retriveCertificati("0", CaGui.CERTIFICATI_VALIDI);                 
        visualizzazione_certificati = CaGui.CERTIFICATI_VALIDI;
        this.popolaTabellaCertificati(c,visualizzazione_certificati);         
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        Vector <Certificato> c = GestioneSQLite.retriveCertificati("0", CaGui.CERTIFICATI_RINNOVATI);                
        visualizzazione_certificati = CaGui.CERTIFICATI_RINNOVATI;        
        this.popolaTabellaCertificati(c,visualizzazione_certificati);          
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:
        Vector <Certificato> c = GestioneSQLite.retriveCertificati("0", CaGui.CERTIFICATI_VALIDI);                
        visualizzazione_certificati = CaGui.CERTIFICATI_SCADUTI;        
        this.popolaTabellaCertificati(c,visualizzazione_certificati); 
    }//GEN-LAST:event_jButton5ActionPerformed

    private void eliminaRichiestaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eliminaRichiestaButtonActionPerformed
        // TODO add your handling code here:
        int rigaSelezionata = jtable_richieste.getSelectedRow();
            if(rigaSelezionata > -1){
                String utente = (String) jtable_richieste.getValueAt(rigaSelezionata, 0); 
                String tipo =(String) jtable_richieste.getValueAt(rigaSelezionata, 1);
                
                GestioneSQLite.eliminaRichieste(utente, tipo);
                this.aggiorna();
        }
    }//GEN-LAST:event_eliminaRichiestaButtonActionPerformed

    public void start(){
        try {
            ca.start();
        } catch (IOException ex) {
            Logger.getLogger(CaGui.class.getName()).log(Level.SEVERE, null, ex);
            this.status.setText("Server non avviato");

        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try{
                CaGui cag = new CaGui();
                cag.aggiorna();             

                cag.setVisible(true);
                cag.status.setText("Server creato");

                cag.start();
                cag.status.setText("Server avviato e in attesa di richieste");
            
                AggiornaThread agg = new AggiornaThread(cag);
                agg.start();
                }catch(Exception e){
                
                }
                
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton eliminaRichiestaButton;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton jbutton_aggiorna;
    private javax.swing.JButton jbutton_approva_certificato;
    private javax.swing.JTable jtable_certificati;
    private javax.swing.JTable jtable_profili;
    private javax.swing.JTable jtable_richieste;
    private javax.swing.JLabel status;
    private javax.swing.JLabel titolo;
    private javax.swing.JButton tutti_certificati;
    // End of variables declaration//GEN-END:variables
}

class AggiornaThread extends Thread {
    CaGui cag;
    String last_change;
    AggiornaThread(CaGui caGui) {
        this.cag=caGui;
        this.last_change=this.cag.ca.getLastCall().toString();
    }

    public void run() {
        try {
            while(true){
                AggiornaThread.sleep(2000);
                if(!cag.ca.getLastCall().toString().equals(last_change)){
                    last_change = cag.ca.getLastCall().toString();
                    cag.aggiorna();                                    
                }
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(AggiornaThread.class.getName()).log(Level.SEVERE, null, ex);
        }             
    }
}